<script setup lang="ts">
  import { ref, reactive } from 'vue'
  import { ElMessage } from 'element-plus'
  import type { ComponentSize } from 'element-plus'
  import { onMounted } from 'vue'
  import { getList, addTrademark, updateTrademark, deleteTrademark, getTrademark } from '@/api/product/trademark'
  import type { TrademarkVo } from '@/api/product/type'
  // 分页器当前的页码数
  const page = ref(1)
  // 分页器每页显示多少条数据
  const pageSize = ref(8)
  //分页器大小
  const size = ref<ComponentSize>('default')
  // 分页器背景颜色，是/否
  const background = ref(true)
  // 是否禁用分页器
  const disabled = ref(false)
  // 总条数
  const total = ref(0)
  //定义一个收集表单数据的对象
  const trademarkForm = reactive<TrademarkVo>({
    id: '',
    trademarkName: '',
    logoUrl: ''
  })
  //定一个表单的实力对象
  const trademarkFormRef = ref()
  //定义一个规则校验对象
  const rules = reactive({
    trademarkName: [
      { required: true, message: '请输入品牌名称', trigger: 'blur' },
      {
        min: 2,
        max: 10,
        message: '品牌名称长度在 2 到 10 个字符',
        trigger: 'blur'
      }
    ],
    logoUrl: [{ required: true, message: '请上传品牌图片', trigger: 'blur' }]
  })
  //每页条数发生变化的时候触发
  const handleSizeChange = (val: number) => {
    console.log(`${val} items per page`)
    getTrademarkList()
  }
  //当前页码变化的时候触发
  const handleCurrentChange = (val: number) => {
    console.log(`current page: ${val}`)
    getTrademarkList()
  }
  const tableData = ref<TrademarkVo[]>([])
  onMounted(() => {
    getTrademarkList()
  })
  //分装一个方法用于获取分页器数据
  async function getTrademarkList() {
    const result = await getList(page.value, pageSize.value)
    total.value = result.total
    tableData.value = result.records
  }
  //对话框的显示/隐藏
  let dialogVisible = ref<Boolean>(false)
  //对话框的标题
  let title = ref<string>('')

  /**
   * 点击添加品牌
   */
  const saveTrademark = () => {
    title.value = '添加品牌'
    dialogVisible.value = true
  }
  /**
   * 点击修改品牌
   * @param id
   */
  const changeTrademark = async (id: string) => {
    getTrademarkInfo(id)
    title.value = '修改品牌'
  }
  /**
   * 删除品牌
   * @param id
   */
  const deleteTrademarkInfo = async (id: string) => {
    await deleteTrademark(id)
    ElMessage.success('删除品牌成功')
    getTrademarkList()
  }
  /**
   * 查看详情
   * @param id
   */
  const getTrademarkInfo = async (id: string) => {
    dialogVisible.value = true
    title.value = '查看详情'
    const { trademarkName, logoUrl } = await getTrademark(id)
    trademarkForm.trademarkName = trademarkName
    trademarkForm.logoUrl = logoUrl
    trademarkForm.id = id
  }
  //对话框关闭
  const handleClose = () => {
    //需要清空表单数据
    trademarkFormRef.value.resetFields()
    trademarkForm.id = ''
    dialogVisible.value = false
  }
  //对话框确定按钮
  const changeConfirm = async () => {
    //先去校验表单数据是否合法
    await trademarkFormRef.value.validate()
    //编辑
    if (trademarkForm.id) {
      await updateTrademark(trademarkForm)
      ElMessage.success('修改品牌成功')
    } else {
      //新增
      await addTrademark(trademarkForm)
      ElMessage.success('添加品牌成功')
    }
    getTrademarkList()
    //需要清空表单数据
    trademarkFormRef.value.resetFields()
    trademarkForm.id = ''
    dialogVisible.value = false
  }
  /**
   * 上传文件之前的钩子函数，可以用来检查文件格式和文件大小
   * @param rawFile
   */
  const beforeAvatarUpload = (rawFile: any) => {
    const allowedTypes = ['image/jpeg', 'image/png', 'image/gif']
    if (!allowedTypes.includes(rawFile.type)) {
      ElMessage.error('上传的文件只能是 JPG、PNG、GIF 格式!')
      return false
    }
    if (rawFile.size / 1024 / 1024 > 5) {
      ElMessage.error('上传的文件大小不能超过 5MB!')
      return false
    }
    return true
  }
  /**
   * 上传成功之后的钩子函数
   * @param response
   * @param uploadFile
   */
  const handleAvatarSuccess = (response: any, uploadFile: any) => {
    //console.log(response.data)
    console.log(uploadFile)
    //收集上传完成之后服务器返回的地址
    trademarkForm.logoUrl = response.data.fileDownloadUri
  }
</script>
<template>
  <div>
    <!-- 卡片组件 -->
    <el-card style="max-width: 100%">
      <el-button @click="saveTrademark" type="primary" icon="Plus">添加商品</el-button>
      <!-- 放置一个表格组件,用来展示数据 -->
      <el-table :data="tableData" style="width: 100%; margin: 10px 0" border>
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="trademarkName" label="品牌名称" align="center" />
        <el-table-column prop="logoUrl" label="LOG" align="center">
          <template #default="{ row }">
            <div style="display: flex; justify-content: center; align-items: center">
              <img :src="row.logoUrl" alt="品牌LOGO" style="width: 50px; height: 50px; border-radius: 50%" />
            </div>
          </template>
        </el-table-column>

        <el-table-column header-align="center" align="center" prop="prop" label="操作label">
          <template #default="{ row }">
            <el-button @click="changeTrademark(row.id)" size="small" type="warning" icon="Edit">编辑</el-button>
            <el-button @click="deleteTrademarkInfo(row.id)" size="small" type="danger" icon="Delete">删除</el-button>
            <el-button @click="getTrademarkInfo(row.id)" size="small" type="success"> 查看详情 </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器组件 
       v-model:current-page:设置当前页码
       v-model:page-size:设置每页展示数据的条数
       :page-sizes="[100, 200, 300, 400]":设置每页展示条数的选项
       :size="size":设置分页器的大小
       :background="background":设置分页器的背景
    -->
      <el-row type="flex" justify="center" style="margin-top: 20px">
        <el-col :span="12">
          <!-- 表格下方放置一个分页组件 -->
          <el-pagination
            v-model:current-page="page"
            v-model:page-size="pageSize"
            :page-sizes="[8, 20, 30, 40]"
            :size="size"
            :disabled="disabled"
            :background="background"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
        </el-col>
      </el-row>
    </el-card>
    <!-- 对话框组件 -->
    <el-dialog center v-model="dialogVisible" :title="title" width="500" :before-close="handleClose">
      <el-form ref="trademarkFormRef" :rules="rules" label-width="auto" :model="trademarkForm" style="max-width: 80%">
        <el-form-item prop="trademarkName" label="品牌名称" label-width="80">
          <el-input placeholder="请输入品牌的名称" v-model="trademarkForm.trademarkName"></el-input>
        </el-form-item>
        <el-form-item prop="logoUrl" v-model="trademarkForm.logoUrl" label="logo" label-width="80">
          <!-- 
          el-upload:上传组件
          action:上传的地址<必须得属性> 记住如果使用默认自动上传,那么action必须是加上我们vite中上传的前缀/dev-api
          :show-file-list="false":是否显示上传的文件列表
          :on-success="handleAvatarSuccess":上传成功的回调函数
          :before-upload="beforeAvatarUpload":上传之前的回调函数
          -->
          <el-upload class="avatar-uploader" action="/dev-api/common/uploadFile" :show-file-list="false" :before-upload="beforeAvatarUpload" :on-success="handleAvatarSuccess">
            <img v-if="trademarkForm.logoUrl" :src="trademarkForm.logoUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <!-- 传入一个具名插槽 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose" v-if="title !== '查看详情'">取消</el-button>
          <el-button v-else @click="handleClose">关闭</el-button>
          <el-button v-if="title !== '查看详情'" type="primary" @click="changeConfirm"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style>
  .avatar {
    width: 178px;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }

  .avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
  }

  .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
  }
</style>
